//
//  LayerHugeCountUseOptimizeViewController.m
//  CoreAnimation
//
//  Created by 张国文 on 16/11/4.
//  Copyright © 2016年 hangzhouyijiyin. All rights reserved.
//

#import "LayerHugeCountUseOptimizeViewController.h"

#define WIDTH 10
#define HEIGHT 10
#define DEPTH 10
#define SIZE 100
#define SPACING 150
#define CAMERA_DISTANCE 500
#define PERSPECTIVE(z) (float)CAMERA_DISTANCE/(z + CAMERA_DISTANCE)

@interface LayerHugeCountUseOptimizeViewController ()<UIScrollViewDelegate>

@property (nonatomic, strong) UIScrollView *scrollView;

@end

@implementation LayerHugeCountUseOptimizeViewController

- (BOOL)shouldAutorotate
{
    return NO;
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskLandscapeLeft;
}

- (void)viewWillAppear:(BOOL)animated
{
    NSLog(@"viewWillAppear");
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    NSLog(@"DidLoad");
    self.view.backgroundColor = [UIColor whiteColor];
    
    
    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.height, self.view.frame.size.width)];
    self.scrollView.backgroundColor = [UIColor blackColor];
    self.scrollView.contentSize = CGSizeMake((WIDTH - 1) * SPACING, (HEIGHT - 1) * SPACING);
    self.scrollView.delegate = self;
    [self.view addSubview:_scrollView];
    
    CATransform3D transform3D = CATransform3DIdentity;
    transform3D.m34 = - 1.0 / CAMERA_DISTANCE;
    self.scrollView.layer.sublayerTransform = transform3D;
    
//    
    UIButton *returnButton = [UIButton buttonWithType:UIButtonTypeCustom];
    returnButton.backgroundColor = [UIColor cyanColor];
    returnButton.bounds = CGRectMake(0, 0, 30, 30);
    returnButton.center = CGPointMake(self.scrollView.center.x, self.scrollView.center.y);
    [returnButton addTarget:self action:@selector(returnBack:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:returnButton];
    
   
}

- (void)returnBack:(UIButton *)button
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)viewDidLayoutSubviews
{
    NSLog(@"viewDidLayoutSubviews");
//    static NSString *bounds = @"YES";
//    if ([bounds isEqualToString:@"YES"]) {
//          [self updateLayers];
//        bounds = @"NO";
//    }
//    [self.view layoutSubviews];
    
      [self updateLayers];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [self updateLayers];
}


- (void)updateLayers
{
    // 计算剪切的矩形范围
    CGRect bounds = self.scrollView.bounds;
    bounds.origin = self.scrollView.contentOffset;
    bounds = CGRectInset(bounds, -SIZE / 2, -SIZE / 2);
    // 创建layers
    NSMutableArray *visibleLayers = [NSMutableArray array];
    for (int z  = DEPTH - 1; z >= 0; z--) {
        // 增加矩形范围来补偿预先显示的范围
        CGRect adjusted = bounds;
        adjusted.size.width /= PERSPECTIVE(z * SPACING);
        adjusted.size.height /= PERSPECTIVE(z * SPACING);
        adjusted.origin.x -= (adjusted.size.width - bounds.size.width) / 2;
        adjusted.origin.y -= (adjusted.size.height - bounds.size.height) / 2;
        for (int y = 0; y < HEIGHT; y++) {
            // 检查垂直的layer是否超过可视矩形的范围
            if (y * SPACING < adjusted.origin.y || y * SPACING >= adjusted.origin.y + adjusted.size.height) {
                continue;
            }
            for (int x = 0; x < WIDTH; x++) {
                // 检查水平的layer是否超过可视矩形的范围
                if (x * SPACING < adjusted.origin.x || x * SPACING >= adjusted.origin.x + adjusted.size.width) {
                    continue;
                }
                // 说明在可视范围
                CALayer *layer = [CALayer layer];
                layer.frame = CGRectMake(0, 0, SIZE, SIZE);
                layer.position = CGPointMake(x * SPACING, y * SPACING);
                layer.zPosition = - z * SPACING;
                layer.backgroundColor = [UIColor colorWithWhite:1 - z *(1.0 / DEPTH) alpha:1].CGColor;
                [visibleLayers addObject:layer];
                [self.scrollView.layer addSublayer:layer];
            }
        }
    }
    NSLog(@"visiblieLayers=%@", visibleLayers);
    for (int i = 0; i < visibleLayers.count; i++) {
        if ([visibleLayers[i] isKindOfClass:[NSNull class]]) {
            [visibleLayers removeObjectAtIndex:i];
        }
    }
    self.scrollView.layer.sublayers = visibleLayers; // 再次赋值的时候会崩溃
    NSLog(@"可视矩形范围中的layer数量：%ld, 总的layer数量:%i", [visibleLayers count], DEPTH * HEIGHT * WIDTH);
 
}


@end
